<template>
  <div class="app-container">
    <div class="top">
      <div>
        <el-select v-model="params.box_number" placeholder="根据号箱进行搜索" clearable @change="delete params.model, params.currentPage = 1,getList()">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.box_number + '号箱'"
            :value="item.box_number"
          />
        </el-select>
        <el-select v-model="params.model" placeholder="根据型号进行搜索" clearable style="margin-left:20px" @change="delete params.box_number, params.currentPage = 1,getList()">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.model"
            :value="item.model"
          />
        </el-select>
        <el-input v-model="params.color" placeholder="请输入颜色进行查询" class="input-with-select" style="width:300px;margin-left: 20px;" @change="params.currentPage = 1,getList()">
          <el-button slot="append" icon="el-icon-search" @click="params.currentPage = 1,getList()" />
        </el-input>
        <el-button
          type="danger"
          style="margin-left: 20px;"
          @click="handleDelete"
        >批量删除</el-button>
      </div>
      <el-button
        type="primary"
        @click="show = true"
      >入库</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      highlight-current-row
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <el-table-column
        align="center"
        type="selection"
        width="55"
      />
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="箱号" align="center" sortable="custom" prop="box_number">
        <template slot-scope="scope">
          {{ scope.row.box_number !== null ? scope.row.box_number + "号箱" : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="型号" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.model || "-" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="颜色" align="center">
        <template slot-scope="scope">
          {{ scope.row.color || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="num" sortable="custom">
        <template slot-scope="scope">
          {{ scope.row.num !== null ? scope.row.num : "-" }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="create_time" sortable="custom">
        <template slot-scope="scope">
          {{ formatterDate(scope.row.create_time) || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center">
        <template slot-scope="scope">
          {{ formatterDate(scope.row.update_time) || "-" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="handleEdit(scope.row)"
          >编辑</el-button>
          <el-button
            type="danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="total"
      :current-page="params.currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="params.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin:20px"
      @size-change="limitchange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      :title="form.id ? '编辑':'添加'"
      :visible.sync="show"
      width="500px"
      :close-on-click-modal="false"
      :before-close="resetFields"
    >
      <el-form ref="ruleForm" :model="form" label-width="120px" :rules="rules" class="pt-20">
        <el-form-item label="请输入箱号" prop="box_number">
          <el-select v-model="form.box_number" placeholder="请选择箱号" clearable style="width:100%" :disabled="Boolean(form.id)" @change="changeBox">
            <el-option v-for="item in options" :key="item.id" :label="item.box_number + '号箱'" :value="item.box_number" />
          </el-select>
        </el-form-item>
        <el-form-item label="请输入型号" prop="model">
          <el-input v-model="form.model" autocomplete="off" disabled placeholder="请先选择箱号" />
        </el-form-item>
        <el-form-item label="请输入颜色" prop="color">
          <el-input v-model="form.color" autocomplete="off" />
        </el-form-item>
        <el-form-item label="请输入数量" prop="num">
          <!-- <el-input v-model="form.num" autocomplete="off" /> -->
          <el-input-number v-model="form.num" :min="0" label="描述文字" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetFields()">取 消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProductsList, delProducts, updateProducts, addProducts, getBoxsList } from '@/api/table'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      show: false,
      form: {
        box_number: '', model: '', color: '', num: '', id: null
      },
      rules: {
        box_number: [
          { required: true, message: '请输入箱子号', trigger: ['blur', 'change'] },
          { pattern: /^\d+$/, message: '请输入整数', trigger: ['blur', 'change'] }
        ],
        model: [
          { required: true, message: '请输入型号', trigger: ['blur', 'change'] }
        ],
        color: [
          { required: true, message: '请输入颜色', trigger: ['blur', 'change'] }
        ],
        num: [
          { required: true, message: '请输入数量', trigger: ['blur', 'change'] },
          { pattern: /^(0|[1-9][0-9]*)(\.[0-9]{0,2})?$/, message: '请输入数字,只允许两位小数', trigger: ['blur', 'change'] }
        ]
      },
      params: {
        pageSize: 10,
        currentPage: 1,
        box_number: null,
        model: null
      },
      total: 0,
      options: [],
      multipleSelection: []
    }
  },
  created() {
    this.getList()
    this._getAllBoxs()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log('val', val)
    },
    sortChange({ prop, order }) {
      const obj = {
        ascending: 'asc',
        descending: 'desc',
        null: 'asc'
      }
      this.params.currentPage = 1
      this.params.sortStr = prop
      this.params.sortType = obj[order]
      console.log('this.params', this.params)
      this.getList()
    },
    changeBox(e) {
      const item = this.options.find(item => item.box_number === e)
      this.form.model = item && item.model || null
      this.form.box_id = item && item.id || null
    },
    async _getAllBoxs() {
      const data = await getBoxsList({ pageSize: 999 })
      console.log(data)
      this.options = data.list
    },
    // 显示分页 当前第几页
    handleCurrentChange(index) {
      this.params.currentPage = index
      this.getList()
    },
    limitchange(val) {
      this.params.currentPage = 1
      this.params.pageSize = val
      this.getList()
    },
    async submit() {
      await this.$refs['ruleForm'].validate()
      const requestFn = this.form.id ? updateProducts : addProducts
      await requestFn(this.form)
      this.getList()
      this.$message.success(`${this.form.id ? '编辑' : '新增'}成功`)
      this.resetFields()
    },
    async resetFields() {
      await this.$refs['ruleForm'].resetFields()
      this.form = {
        box_number: '', model: '', color: '', num: '', id: null
      }
      this.show = false
    },
    handleEdit(item) {
      this.form = JSON.parse(JSON.stringify(item))
      this.show = true
    },
    async handleDelete(item) {
      console.log('this', this.multipleSelection, ids)
      if (typeof item.id !== 'number' && !this.multipleSelection.length) return this.$message.error('请选择列表项进行操作')
      await this.$confirm(`${Number(item.num) > 0 ? `该产品数量还剩${item.num}件,数据删除后不可恢复！` : ''} 确定要删除${typeof item.id === 'number' ? '该' : '选择的'}产品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      const isNumOver = this.multipleSelection.some(item => item.num > 0)
      console.log('isNumOver', isNumOver)
      if (isNumOver) {
        await this.$confirm(`您选择的产品中，有产品的数量不为0，数据删除后不可恢复！请再次确认要删除吗？`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
      }
      const ids = typeof item.id === 'number' ? [item.id] : this.multipleSelection.map(item => item.id)
      await delProducts({ ids })
      this.$message.success('删除成功')
      this.list.length === 1 && this.params.currentPage > 1 ? this.params.currentPage -= 1 : ''
      this.getList()
    },
    formatterDate(data) {
      const originalDate = new Date(data)
      const formattedDate = originalDate
        .toLocaleString('en-US', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        })
        .replace(/,/g, '')
        .replace(/\//g, '-')
      return formattedDate
    },
    getList() {
      this.listLoading = true
      getProductsList(this.params).then((res) => {
        console.log('res', res)
        this.list = res.list
        this.total = res.total
        this.listLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>
